/**
 * 实时市场指数数据钩子（WebSocket增强版）
 * 
 * 功能：
 * 1. 优先使用WebSocket获取实时数据
 * 2. WebSocket不可用时自动回退到HTTP轮询
 * 3. 智能数据策略选择
 */

import { useEffect, useState, useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { get } from '@shared/utils/apiClient';
import { ApiResponse, IndexData } from '@shared/types/market';
import { getRefreshInterval } from '@shared/utils/marketStatus';
import { useSmartMarketData, useBatchMarketData } from '@redfire/api-client';

const API_BASE = import.meta.env.VITE_API_BASE_URL || '';

/**
 * 使用WebSocket实时获取单个指数数据
 */
export function useRealtimeIndexData(code: string) {
  // 使用智能数据获取Hook
  const {
    data: wsData,
    error: wsError,
    isLoading: wsLoading,
    strategy,
    isConnected,
    refetch
  } = useSmartMarketData({
    symbol: code,
    updateFrequency: 5000, // 5秒更新
    priority: 'normal',
    fallbackToPolling: true
  });

  // HTTP备用查询
  const refreshInterval = getRefreshInterval();
  
  const {
    data: httpData,
    error: httpError,
    isLoading: httpLoading,
    refetch: httpRefetch
  } = useQuery({
    queryKey: ['indexData', code],
    queryFn: async () => {
      const response = await get<ApiResponse<IndexData>>(
        `${API_BASE}/api/v1/market/index?code=${code}`
      );
      return response.data;
    },
    enabled: strategy === 'polling' || !isConnected,
    refetchInterval: refreshInterval,
    // 休市时增加 staleTime
    staleTime: refreshInterval === 0 ? 300000 : 15000,
    gcTime: 300000,
    refetchOnWindowFocus: false,
    // 休市时禁用自动刷新
    refetchOnMount: refreshInterval > 0,
    refetchOnReconnect: refreshInterval > 0,
    // 保留之前的数据
    placeholderData: (previousData) => previousData,
  });

  // 智能合并数据：WebSocket数据优先，但保留HTTP数据的字段
  const mergedData = useMemo(() => {
    if (wsData && httpData) {
      // 合并两者数据，WebSocket优先
      return { ...httpData, ...wsData, _source: 'websocket' };
    }
    return wsData || httpData;
  }, [wsData, httpData]);

  // 只有在没有任何数据且正在加载时才显示 loading
  const shouldShowLoading = (wsLoading || httpLoading) && !mergedData;

  // 返回合并的结果
  return {
    data: mergedData,
    error: wsError || httpError,
    isLoading: shouldShowLoading,
    strategy,
    isConnected,
    refetch: strategy === 'websocket' ? refetch : httpRefetch,
    source: strategy === 'websocket' ? 'WebSocket' : 'HTTP'
  };
}

/**
 * 使用WebSocket实时获取多个指数数据
 */
export function useRealtimeMarketIndexes(codes?: string[]) {
  const defaultCodes = codes || ['000001.SH', '399001.SZ', '399006.SZ', 'HSI'];
  
  console.log('[useRealtimeMarketIndexes] 初始化');
  console.log('[useRealtimeMarketIndexes] 传入codes:', codes);
  console.log('[useRealtimeMarketIndexes] 使用defaultCodes:', defaultCodes);

  // 使用批量数据获取Hook
  const {
    data: wsData,
    errors: wsErrors,
    isLoading: wsLoading,
    strategies,
    isConnected,
    refetch: wsRefetch
  } = useBatchMarketData(defaultCodes, {
    updateFrequency: 5000,
    priority: 'normal',
    fallbackToPolling: true
  });
  
  console.log('[useRealtimeMarketIndexes] WebSocket数据:', wsData);
  console.log('[useRealtimeMarketIndexes] WebSocket数据长度:', wsData?.length);
  console.log('[useRealtimeMarketIndexes] WebSocket连接状态:', isConnected);

  // HTTP备用查询（仅在 WebSocket 未连接时启用）
  const refreshInterval = getRefreshInterval();
  
  const {
    data: httpData,
    error: httpError,
    isLoading: httpLoading,
    refetch: httpRefetch
  } = useQuery({
    queryKey: ['marketIndexes', codes],
    queryFn: async () => {
      const params = defaultCodes ? `?codes=${defaultCodes.join(',')}` : '';
      const url = `${API_BASE}/api/v1/market/indexes${params}`;
      console.log('[useRealtimeMarketIndexes] 请求URL:', url);
      console.log('[useRealtimeMarketIndexes] 请求codes:', defaultCodes);
      
      const response = await get<ApiResponse<IndexData[]>>(url);
      console.log('[useRealtimeMarketIndexes] API响应:', response);
      console.log('[useRealtimeMarketIndexes] 返回数据数量:', response.data?.length);
      console.log('[useRealtimeMarketIndexes] 返回数据:', response.data);
      
      return response.data;
    },
    // 只在 WebSocket 未连接时才启用 HTTP 查询
    enabled: !isConnected,
    refetchInterval: refreshInterval,
    // 休市时增加 staleTime，避免频繁标记为 loading
    staleTime: refreshInterval === 0 ? 300000 : 15000,
    gcTime: 300000,
    refetchOnWindowFocus: false,
    // 休市时禁用自动重新挂载请求
    refetchOnMount: refreshInterval > 0,
    refetchOnReconnect: refreshInterval > 0,
    // 关键：保留之前的数据，避免显示加载状态
    placeholderData: (previousData) => previousData,
  });

  // 智能合并WebSocket和HTTP数据
  // 策略：使用HTTP数据作为基础，WebSocket数据增量更新
  const mergedData = useMemo(() => {
    // 如果没有HTTP数据，返回WebSocket数据
    if (!httpData || httpData.length === 0) {
      return wsData;
    }
    
    // 如果没有WebSocket数据或未连接，返回HTTP数据
    if (!isConnected || wsData.length === 0) {
      return httpData;
    }
    
    // 合并数据：创建一个Map，先放入HTTP数据，然后WebSocket数据覆盖相同code的项
    const dataMap = new Map<string, any>();
    
    // 1. 先添加所有HTTP数据
    httpData.forEach(item => {
      if (item?.code) {
        dataMap.set(item.code, item);
      }
    });
    
    // 2. WebSocket数据覆盖/更新
    wsData.forEach(item => {
      if (item?.code || item?.symbol) {
        const key = item.code || item.symbol;
        dataMap.set(key, {
          ...dataMap.get(key), // 保留HTTP数据的其他字段
          ...item,              // WebSocket数据覆盖
          _source: 'websocket'  // 标记数据来源
        });
      }
    });
    
    return Array.from(dataMap.values());
  }, [httpData, wsData, isConnected]);
  
  const primaryStrategy = strategies[0] || 'polling';
  
  console.log('[useRealtimeMarketIndexes] HTTP数据:', httpData);
  console.log('[useRealtimeMarketIndexes] HTTP数据长度:', httpData?.length);
  console.log('[useRealtimeMarketIndexes] WebSocket数据长度:', wsData?.length);
  console.log('[useRealtimeMarketIndexes] 合并后数据:', mergedData);
  console.log('[useRealtimeMarketIndexes] 合并后数据长度:', mergedData.length);
  console.log('[useRealtimeMarketIndexes] 数据来源分布:', {
    httpOnly: mergedData.filter(d => !d?._source).length,
    websocketUpdated: mergedData.filter(d => d?._source === 'websocket').length
  });
  console.log('[useRealtimeMarketIndexes] 最终返回:', {
    dataLength: mergedData.length,
    codes: mergedData.map(d => d?.code || d?.symbol),
    isConnected,
    strategy: primaryStrategy
  });

  // 修复加载逻辑：只有在没有任何数据且正在加载时才显示 loading
  // 如果已有数据（合并数据长度 > 0），则不应该显示 loading
  const shouldShowLoading = (wsLoading || httpLoading) && (!mergedData || mergedData.length === 0);
  
  console.log('[useRealtimeMarketIndexes] Loading状态:', {
    wsLoading,
    httpLoading,
    hasData: mergedData && mergedData.length > 0,
    shouldShowLoading
  });

  return {
    data: mergedData,
    error: wsErrors[0] || httpError,
    errors: wsErrors,
    isLoading: shouldShowLoading,
    strategy: primaryStrategy,
    strategies,
    isConnected,
    refetch: isConnected ? wsRefetch : httpRefetch,
    source: isConnected ? 'WebSocket' : 'HTTP'
  };
}

/**
 * 实时数据流Hook
 * 只使用WebSocket，不回退到HTTP
 */
export function useRealtimeDataStream(symbol: string) {
  const [data, setData] = useState<any>(null);
  const [updateCount, setUpdateCount] = useState(0);
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null);

  const {
    data: streamData,
    isConnected,
    strategy
  } = useSmartMarketData({
    symbol,
    updateFrequency: 1000, // 1秒更新
    priority: 'realtime',
    fallbackToPolling: false // 不回退到HTTP
  });

  // 监听数据更新
  useEffect(() => {
    if (streamData && streamData !== data) {
      setData(streamData);
      setUpdateCount(prev => prev + 1);
      setLastUpdate(new Date());
    }
  }, [streamData]);

  return {
    data,
    isConnected,
    strategy,
    updateCount,
    lastUpdate,
    isRealtime: strategy === 'websocket' && isConnected
  };
}

/**
 * 市场数据监控Hook
 * 用于显示连接状态和数据质量指标
 */
export function useMarketDataMonitor() {
  const [metrics] = useState({
    isConnected: false,
    connectionQuality: 'unknown' as 'good' | 'fair' | 'poor' | 'unknown',
    latency: 0,
    updateRate: 0,
    dataFreshness: 'stale' as 'fresh' | 'stale' | 'very_stale'
  });

  // 这里可以添加实际的监控逻辑
  // 比如从WebSocket管理器获取连接状态和性能指标

  return metrics;
}

/**
 * WebSocket连接状态Hook
 */
export function useWebSocketStatus() {
  const [status] = useState({
    isConnected: false,
    reconnectAttempts: 0,
    lastError: null as Error | null,
    connectionTime: null as Date | null
  });

  // 这里可以添加实际的状态监听逻辑
  // 从WebSocket管理器订阅状态变化

  return status;
}

